package com.we.risk.registerorigin.table;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class TableMkPassBackRecordPart27 {
    public static final String UTMSOURCE = "oppo";
    public static final String KFKTABLE = "fdm.hhl10_mk_pass_back_record_part27";
    public static final String QUERYSQL =
            "select uid, "
                    + "'oppo' AS utm_source, "
                    +
                    //            "'null' as ad_group, 'null' as keyword, " +
                    "campaign_id AS advert, "
                    + "unix_timestamp(date_format(update_time,'yyyy-MM-dd HH:mm:ss')) as update_time "
                    + "from "
                    + KFKTABLE
                    + " where update_time is not null";

    public long uid;
    public String utm_source;
    public String advert;
    //    public String keyword;
    //    public String ad_group;
    public long update_time;

    public TableMkPassBackRecordPart27() {}

    public TableMkPassBackRecordPart27(
            long uid, String utm_source, String advert, long update_time) {
        this.uid = uid;
        this.utm_source = utm_source;
        this.advert = advert;
        //        this.keyword = keyword;
        //        this.ad_group = ad_group;
        this.update_time = update_time;
    }

    public static TableMkPassBackRecordPart27 init(long uid) {
        return new TableMkPassBackRecordPart27(uid, "xiaomi-ocpd", null, Long.MAX_VALUE);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {
        Table tableRes = tableEnv.sqlQuery(TableMkPassBackRecordPart27.QUERYSQL);
        DataStream<Tuple2<Boolean, TableMkPassBackRecordPart27>> input =
                tableEnv.toRetractStream(tableRes, TableMkPassBackRecordPart27.class);

        SingleOutputStreamOperator<String> out =
                input.filter(
                                new FilterFunction<Tuple2<Boolean, TableMkPassBackRecordPart27>>() {
                                    @Override
                                    public boolean filter(
                                            Tuple2<Boolean, TableMkPassBackRecordPart27> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TableMkPassBackRecordPart27-filter")
                        .keyBy(
                                new KeySelector<
                                        Tuple2<Boolean, TableMkPassBackRecordPart27>, Long>() {
                                    @Override
                                    public Long getKey(
                                            Tuple2<Boolean, TableMkPassBackRecordPart27> value)
                                            throws Exception {
                                        return value.f1.getUid();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<
                                        Tuple2<Boolean, TableMkPassBackRecordPart27>, String>() {
                                    ValueState<TableMkPassBackRecordPart27>
                                            tableMkPassBackRecordPart27VState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        tableMkPassBackRecordPart27VState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TableMkPassBackRecordPart27>(
                                                                        "TableMkPassBackRecordPart22VState",
                                                                        TableMkPassBackRecordPart27
                                                                                .class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableMkPassBackRecordPart27> value,
                                            Collector<String> out)
                                            throws Exception {
                                        long uid = value.f1.getUid();
                                        long update_time = value.f1.getUpdate_time();

                                        TableMkPassBackRecordPart27 tmpState =
                                                tableMkPassBackRecordPart27VState.value();
                                        TableMkPassBackRecordPart27 curState =
                                                tmpState == null
                                                        ? TableMkPassBackRecordPart27.init(uid)
                                                        : tmpState;

                                        if (update_time < curState.update_time) {
                                            String advert = value.f1.getAdvert();
                                            JSONObject outJson = new JSONObject();
                                            outJson.put("uid", uid);
                                            outJson.put("update_time", update_time);
                                            outJson.put("utm_source", UTMSOURCE);
                                            outJson.put("advert", advert);
                                            outJson.put("ad_group", null);
                                            outJson.put("key_word", null);
                                            out.collect(
                                                    outJson.toString(
                                                            SerializerFeature.WriteMapNullValue));

                                            curState.advert = advert;
                                            curState.update_time = update_time;
                                            tableMkPassBackRecordPart27VState.update(curState);
                                        }
                                    }
                                });
        return out;
    }

    public long getUid() {
        return uid;
    }

    public String getUtm_source() {
        return utm_source;
    }

    public String getAdvert() {
        return advert;
    }

    public long getUpdate_time() {
        return update_time;
    }
}
